package com.finance.util.encrypt;

import com.finance.util.CertificateCoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

public class Base64ImgUtil {
	static Logger logger = LoggerFactory.getLogger(CertificateCoder.class);
    /**
     * 微信图片进行处理
     *
     * @param imgBase64Content
     * @return
     * @throws UnsupportedEncodingException 
     */
    public static  InputStream handleBase64IMG(String imgBase64Content){
    	String tinyImageData = null;
		try {
			tinyImageData = URLDecoder.decode(imgBase64Content, "UTF-8");
			//解决文件内容在传递过程中多次加密的情况
 			while(tinyImageData.contains("%")){
 				tinyImageData = URLDecoder.decode(imgBase64Content, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
	 		logger.error(e.getMessage(),e);
	 		return null;
		}
		String[] contents = tinyImageData.split(";base64,");
 		try {
			return new ByteArrayInputStream(decode(contents[1]));
		} catch (IOException e) {
 			logger.error(e.getMessage(),e);
		}
		return null;
     }
    /**
     * 对图片进行转码
     *
     * @param imageData 图片BASE64编码
     * @return 字节流
     * @throws IOException
     */
    private static byte[] decode(String imageData) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] data = decoder.decodeBuffer(imageData);
        for (int i = 0; i < data.length; ++i) {
            if (data[i] < 0) {
                data[i] += 256;
            }
        }
        return data;
    }
}
